package com.hz.handler;


import com.hz.utils.ResultData;
import com.hz.utils.ResultUtils;
import com.hz.pojo.User;
import com.hz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//允许跨域
//@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserC {

    @Autowired
    private UserService service;

    @PostMapping("/login")
    public ResultData login(@RequestBody User user) {
        User res = service.orLogin(user);
        if (res != null) {
            //登录成功的话创建一个token封装到res对象中
            return ResultUtils.sucuss("success", res);
        } else {
            return ResultUtils.error("用户名和密码不匹配", null);
        }
    }

    @GetMapping("/info")
    public ResultData info(@RequestParam("token") String token) {
        User res = service.getListByToken(token);
        if (res != null) {
            return ResultUtils.sucuss("success", res);
        } else {
            return ResultUtils.error("", null);
        }
    }

    @PostMapping("/logout")
    public ResultData logout(@RequestHeader("X-Token") String token) {
        User res = service.getListByToken(token);
        if (res != null) {
            return ResultUtils.sucuss("success", null);
        } else {
            return ResultUtils.error("退出失败", null);
        }
    }

    //管理员列表
    @GetMapping("list/admin")
    public ResultData listAdmin(User user, @RequestHeader("X-Token") String token) {
        user.setToken(token);
        Map<String, Object>  res = service.listAdmin(user);
        if (res != null) {
            return ResultUtils.sucuss("查询成功", res);
        } else {
            return ResultUtils.error("暂无管理人员", null);
        }
    }

    //新增管理员
    @PostMapping("/create/admin")
    public ResultData add(@RequestBody User user, @RequestHeader("X-Token") String token) {
        user.setToken(token);
        int res = service.addAdmin(user);
        if (res == 1) {
            return ResultUtils.sucuss("新增成功", null);
        } else if (res == 2) {
            return ResultUtils.error("新增失败用户已存在", null);
        } else {
            return ResultUtils.error("新增失败", null);
        }
    }

    //修改信息
    @PostMapping("/update/admin")
    public ResultData update(@RequestBody User user) {
        int res = service.updateAdmin(user);
        if (res != 0) {
            return ResultUtils.sucuss("修改成功", null);
        }  else {
            return ResultUtils.error("修改失败用户已存在", null);
        }
    }

    //删除管理员信息
    @PostMapping("/delete/admin")
    public ResultData delete(@RequestBody User user) {
        int res = service.deleteAdmin(user);
        if (res != 0) {
            return ResultUtils.sucuss("删除成功", null);
        } else {
            return ResultUtils.error("删除失败", null);
        }
    }

}
